package com.controller;

import java.util.List;

import org.activiti.engine.ProcessEngine;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class FlowController {

	@Autowired
	private ProcessEngine processEngine;
	
	/**
	 * 部署流程定义
	 * @return
	 */
	@RequestMapping("deployFlow")
	public String deployFlow(){
		//管理流程定义的service
		RepositoryService repositoryService = processEngine.getRepositoryService();
		
		Deployment deployment = repositoryService.createDeployment().name("helloword流程") //创建一个部署对象
		.addClasspathResource("diagrams/helloword.bpmn") //从classPath中加载资源文件，一次只能加载一个
		.addClasspathResource("diagrams/helloword.png")
		.deploy();//完成部署
		
		System.out.println(deployment.getId() + deployment.getName());
		
		return deployment.getName();
	}
	
	/**
	 * 启动流程实例
	 * @return
	 */
	@RequestMapping("startFlow")
	public String startFlow(){
		
		String processDefinitionKey = "helloword1";
		
		//正在执行的流程实例和执行对象相关的service
		RuntimeService runtimeService = processEngine.getRuntimeService();
		
		//使用流程定义的key启动流程实例，key对应的是bpmn文件中的id，默认是最新版本的流程启动
		ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(processDefinitionKey);
		
		System.out.println(processInstance.getId() + processInstance.getProcessDefinitionId());
		
		return processInstance.getProcessDefinitionId();
	}
	
	/**
	 * 查询当前人的个人任务
	 * @return
	 */
	@RequestMapping("findPersonalTask")
	public String findPersonalTask(){
		
		String assignee = "李四";
		
		List<Task> list = processEngine.getTaskService()
		.createTaskQuery()
		.taskAssignee(assignee).list();
		
		if(!CollectionUtils.isEmpty(list)){
			for (Task task : list) {
				System.out.println(task.getAssignee());
				System.out.println(task.getId());
				System.out.println(task.getName());
				System.out.println(task.getExecutionId());
			}
		}
		
		System.out.println("****************");
		
		return list.toString();
	}
	
	/**
	 * 完成我的任务
	 * @return
	 */
	@RequestMapping("completePersonalTask")
	public String completePersonalTask(){
		
		String taskId = "5002";
		
		processEngine.getTaskService().complete(taskId);
		
		return "完成任务" + taskId;
	}
	
}
